package com.newture.lxz.services.impl;

import com.newture.lxz.constant.Constant;
import com.newture.lxz.db.mapper.LdMailMapper;
import com.newture.lxz.db.model.*;
import com.newture.lxz.errors.AppException;
import com.newture.lxz.errors.Errors;
import com.newture.lxz.pvg.Pvg;
import com.newture.lxz.services.ICourtAddressSrv;
import com.newture.lxz.services.IMailSrv;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Service("MailSrv")
public class MailSrv implements IMailSrv {

    @Resource
    LdMailMapper ldMailMapper;
    @Override
    public int insert(LdMail obj) {
        obj.setCreator(Pvg.getPvgName());
        obj.setModifier(Pvg.getPvgName());
        obj.setGmtCreated(LocalDateTime.now());
        obj.setIsDeleted(Constant.NO);
        obj.setVersion(1);
        int effectCount = ldMailMapper.insert(obj);
        if(effectCount != 1) {
            throw new AppException(Errors.SAVE_ERR.name(), obj.toString(), "MainSrv.insert() failed");
        }

        return obj.getId();
    }

    @Override
    public LdMail findById(int id, String[] columns) {

        LdMailExample example = new LdMailExample();
        LdMailExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(id);
        criteria.andIsDeletedEqualTo(Constant.NO);

        example.setDynamicColumns(columns);
        List<LdMail> list = ldMailMapper.selectByExample(example);
        if(list.isEmpty()) {
            throw new AppException(Errors.NO_RECORD_FOUND_BY_ID.name(),
                    String.format("ID is %s", id), "No record found in CourtAddressSrv.findById()");
        }

        if(list.size() > 1) {
            throw new AppException(Errors.MORE_THAN_ONE_RECORDS_FOUND.name(),
                    String.format("ID is %s", id), "More than one record found in CourtAddressSrv.findById()");
        }

        return list.get(0);
    }
}
